//$.fn 是往jQuery原型上扩展方法
//$.extend 扩展工具方法 
;(function($){
    "use strict";

    function createXHR(){
        if(XMLHttpRequest){
            return new XMLHttpRequest()
        }
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    //全局方法
    $.getParams=function(obj){
        var str="";
        for (let key in obj){
            str+=key+"="+obj[key]+"&"
        }
        return str;
    }
    $Myajax=function(opts){
        var xhr=createXHR();
        opts.type = opts.type == undefined ? "get" : opts.type;
        opts.async = opts.async == undefined ? true : opts.async
        if (opts.type == "get") {
            //url
            xhr.open("get", opts.url + "?" + $.getParams(opts.data), opts.async);
            xhr.send(null);
        } else {
            xhr.open("post", opts.url, opts.async);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send($.getParams(opts.data));
        }
        //接受结果的时候,是同步还是异步
        if (opts.async == true) { //异步
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        var data = xhr.responseText;
                        if (opts.dataType == "json") {
                            data = JSON.parse(data);
                        }
                        opts.success(data)
                    }
                }
            }
        } else { //同步
            if (xhr.status == 200) {
                var data = xhr.responseText;
                if (opts.dataType == "json") {
                    data = JSON.parse(data);
                }
                opts.success(data)

            }
        }
    }
})(jQuery)